#include "spacecontrolledpipesprite.h"
#include"globalgamemsger.h"
#include<QGraphicsScene>
#include<QPainter>
#include<QtMath>
void SpaceControlledPipeSprite::onJump(float intens)
{
    vy=-intens*k;
}

SpaceControlledPipeSprite::SpaceControlledPipeSprite
(float x0, float y0, float g0,
 float ymax, float ymin,
 bool docount,
 float corrfactor,
 float spd,QObject *)
    :AbstractPipe(x0,y0,docount,spd)
{
    x=x0;
    y=y0;
    g=g0;
    upperBound=ymax;
    lowerBound=ymin;
    vy=0;
    vx=3;
    //connect(&globalGameMsger::m,&globalGameMsger::jump,this,&SpaceControlledPipeSprite::onJump);
    //connect(&globalGameMsger::m,&globalGameMsger::onVoiceAmp,this,&SpaceControlledPipeSprite::SoundAmpJump);
    connect(&globalGameMsger::m,&globalGameMsger::controlByFrequencyAndVolume,this,&SpaceControlledPipeSprite::onFreqAndVolume);

    connect(&globalGameMsger::m,&globalGameMsger::shiftPressed,this,&SpaceControlledPipeSprite::onShiftPressed);
    connect(&globalGameMsger::m,&globalGameMsger::ZPressed,this,&SpaceControlledPipeSprite::onZPressed);

    k=corrfactor;
}

SpaceControlledPipeSprite::~SpaceControlledPipeSprite()
{
}
void SpaceControlledPipeSprite::updateXY()
{
    x-=vx;
    vy+=g;
    y+=vy;
    if(y<lowerBound)y=lowerBound;
            //,vy=0;
    if(y>upperBound)y=upperBound;
    //,vy=0;
}

void SpaceControlledPipeSprite::afterUpdateXY()
{
    if(x<=scene()->sceneRect().width()/2)
    {
        if(Uncounted)
        {
            emit globalGameMsger::m.addScore();
            Uncounted=0;
        }
        //disconnect(&globalGameMsger::m,&globalGameMsger::controlByFrequencyAndVolume,this,&SpaceControlledPipeSprite::onFreqAndVolume);
        //vy=g=0;
    }
    if(x<-PipeImg.width()-20)
    {
        scene()->removeItem(this);
        delete this;
    }
}
void SpaceControlledPipeSprite::onGameOver()
{
    vx=0;
    g=0;
    vy=0;
    disconnect(&globalGameMsger::m,&globalGameMsger::jump,this,&SpaceControlledPipeSprite::onJump);
    disconnect(&globalGameMsger::m,&globalGameMsger::controlByFrequencyAndVolume,this,&SpaceControlledPipeSprite::onFreqAndVolume);
}

void SpaceControlledPipeSprite::onShiftPressed()
{
    vy=5;
}

void SpaceControlledPipeSprite::onZPressed()
{
    vy=vy>0?-vy*2:vy*2;
}

void SpaceControlledPipeSprite::onFreqAndVolume(float freq, float volume)
{
    float intens=log2(freq/220)*12.0/4.0;
    if(isupper)
        vy=(log10(volume/20.0)*(1.0/k)-intens*k);
    else
        vy=(-log10(volume/20.0)*(1.0/k)-intens*k)*1.3;
    //emit globalGameMsger::m.jump(4);
}
void SpaceControlledPipeSprite::SoundAmpJump(float vol)
{
    vy=-k*(vol-35)/2.5;
}
